const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => console.log('数据库连接成功'))
    .catch(err => console.log(err, '数据库连接失败'))

const postSchema = new mongoose.Schema({
    title: {
        type: String,
        //required: true
        required: [true, '请传入文章标题'],
        minlength: [2, '长度不能超过2'],
        maxlength: [5, '...'],
        trim: true   //去除字符串两边的空格
    },
    age: {
        type: Number,
        min: 18,
        max: 100
    },
    publishDate: {
        type: Date,
        default: Date.now
    },
    category: {
        type: String,
        //enum: ['html', 'JavaScript', 'css', 'node.js']
        enum: {
            values: ['html', 'JavaScript', 'css', 'node.js'],
            message: '分类名称要在指定的范围内'
        }
    },
    author: {
        type: String,
        validate: {
            validator: v => {
                //返回布尔值
                //v要验证的值
                return v && v.length > 4
            },
            //自定义错误信息
            message: '传入的值不符合验证规则'
        }
    }
});

const Post = mongoose.model('Post', postSchema);

Post.create({ title: 'aa', age: 23, category: 'haha', author: 'bb' })
    .then(result => console.log(result))
    .catch(error => {
        //获取错误信息对象
        const err = error.errors;
        //循环错误信息对象
        for (var attr in err) {
            console.log(err[attr]['message']);
        }
    })